using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using fads .Model;

namespace fads .DAL
{
	public class page_fieldDAL
	{
		public int AddNew(page_field model)
		{
			object obj = SqlHelper.ExecuteScalar(
				"INSERT INTO page_field(page_operate_id,page_field_code,page_field_name,description,create_time,update_time) VALUES (@page_operate_id,@page_field_code,@page_field_name,@description,@create_time,@update_time);SELECT @@identity"
				,new SqlParameter("@page_operate_id", model.page_operate_id)
				,new SqlParameter("@page_field_code", model.page_field_code)
				,new SqlParameter("@page_field_name", model.page_field_name)
				,new SqlParameter("@description", model.description)
				,new SqlParameter("@create_time", model.create_time)
				,new SqlParameter("@update_time", model.update_time)
			);
			return Convert.ToInt32(obj);
		}

		public bool Delete(int id)
		{
			int rows = SqlHelper.ExecuteNonQuery("DELETE FROM page_field WHERE id = @id", new SqlParameter("@id", id));
			return rows > 0;
		}

		public bool Update(page_field model)
		{
			string sql = "UPDATE page_field SET page_operate_id=@page_operate_id,page_field_code=@page_field_code,page_field_name=@page_field_name,description=@description,create_time=@create_time,update_time=@update_time WHERE id=@id";
			int rows = SqlHelper.ExecuteNonQuery(sql
				, new SqlParameter("@id", model.id)
				, new SqlParameter("@page_operate_id", model.page_operate_id)
				, new SqlParameter("@page_field_code", model.page_field_code)
				, new SqlParameter("@page_field_name", model.page_field_name)
				, new SqlParameter("@description", model.description)
				, new SqlParameter("@create_time", model.create_time)
				, new SqlParameter("@update_time", model.update_time)
			);
			return rows > 0;
		}

		public page_field Get(int id)
		{
			DataTable dt = SqlHelper.ExecuteDataTable("SELECT * FROM page_field WHERE id=@id", new SqlParameter("@id", id));
			if (dt.Rows.Count > 1)
			{
				throw new Exception("more than 1 row was found");
			}
			if (dt.Rows.Count <= 0)
			{
				return null;
			}
			DataRow row = dt.Rows[0];
			page_field model = ToModel(row);
			return model;
		}

		private static page_field ToModel(DataRow row)
		{
			page_field model = new page_field();
			model.id = (object)row["id"];
			model.page_operate_id = (object)row["page_operate_id"];
			model.page_field_code = (string)row["page_field_code"];
			model.page_field_name = (string)row["page_field_name"];
			model.description = (string)row["description"];
			model.create_time = (object)row["create_time"];
			model.update_time = (object)row["update_time"];
			return model;
		}

		public IEnumerable<page_field> ListAll()
		{
			List<page_field> list = new List<page_field>();
			DataTable dt = SqlHelper.ExecuteDataTable("SELECT * FROM page_field");
			foreach (DataRow row in dt.Rows)
			{
				list.Add(ToModel(row));
			}
			return list;
		}
	}
}
